package com.study.spmongodb.book.wwj.char03;

import java.util.concurrent.TimeUnit;

/**
 * @author MI
 * @version 1.0
 * @date 2020/11/24 19:49
 */
public class FlagThreadExit {
    static class MyTask extends Thread {
        private volatile boolean closed = false;

        @Override
        public void run() {

            System.out.println("i will start work");
            while (!closed && !isInterrupted()) {
                //working
            }
            System.out.println("i will be existing");
        }

        public void close() {
            this.closed = true;
            this.interrupt();
        }
    }

    /**
     * 由于线程interrupt标识很有可能被擦除，或者逻辑单元不会调用任何可中断方法，
     * 所有使用volatile 修饰的开关flag关闭线程是一种常用做法。
     */
    public static void main(String[] args) throws InterruptedException {
        final MyTask thread = new MyTask();
        thread.start();
        TimeUnit.SECONDS.sleep(1);
        System.out.println("system will be shutdown");
        thread.close();
    }
}
